import axios from 'axios'
// import store from '@/store'
// import PsMessage from '@/components/message/index'
// import { parseTime } from '@/util'
import { useConfigData } from '@/stores/config-data'
import { useUserInfo } from '@/stores/user-info'
import { storeToRefs } from 'pinia'
import {useEnvConfig} from '@/config'
// create an axios instance
const service = axios.create({
  headers: {
    'content-type': 'application/json'
  },
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

// request interceptor
// 防止多次请求
// let startRefreshTokenFlag = false
service.interceptors.request.use(
  async (config) => {
    if ('dev' === import.meta.env.MODE) {
      config.url = 'http://192.168.100.8:23094'+config.url  
    } else {
      const {ENV_CONFIG} = useEnvConfig()
      config.url = ENV_CONFIG.BASE_URL+''+config.url
    }
    // const userInfoStore = useUserInfo()
    // const { token } = storeToRefs(userInfoStore)

    const configDataStore = useConfigData()
    const userInfoStore = useUserInfo();
    const { token} = storeToRefs(userInfoStore);
    const { configData } = storeToRefs(configDataStore)

    config.headers['version'] = configData.value.version
    config.headers['unionid'] = configData.value.union_id
    config.headers['appid'] = configData.value.app_id

    // 已经登录
    if (token.value) {
      config.headers['Authorization'] = 'Bearer ' + (token.value || '')
      config.headers['Content-Type'] = 'application/json'
    }

    return config

  },
  (error) => {
    // do something with request error

    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const data = response.data
    return data
    
  },
  (error) => {
    return Promise.resolve({
      code:-1,
      data:'',
      msg:error
    })
  }
)

export default service
